﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
public partial class JobManage_PendingJobDetail : BasePage
{

    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IJobHandler jobManage = new JobHandler();
    IBNTruckHandler truckManage = new BNTruckHandler();
    ISystemHandler systemManage = new SystemHandler();
    private static bool isCheck = false;
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1061")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    if (strPermission.Contains("1064"))
                    {
                        btnCheck.Visible = true;
                        isCheck = true;
                    }
                    else
                    {
                        btnCheck.Visible = false;
                        isCheck = false;
                    }
                }
            }
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";

            ViewState["OrderByT"] = "PKID";
            ViewState["AccendingT"] = "desc";
            dataBindDetail(int.Parse(Request["OrderID"]));
            dataBindTruck(GetClientID());
        }
    }


    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }
 

    private void dataBindDetail(int orderID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID",orderID.ToString());
        string sqlStr = "select *,Appointament from BN_ShippingOrderDtl,BN_ShippingOrder where BN_ShippingOrder.PKID=BN_ShippingOrderDtl.OrderID and BN_ShippingOrderDtl.OrderID=@OrderID";
        DataTable dt = jobManage.GetShippingOrderDtl(sqlStr,parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvShipperOrderDetailList.DataSource = view;
        gvShipperOrderDetailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void dataBindTruck(int clientID)
    {
        DataTable dt = truckManage.GetTruckList(clientID);
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }
  

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvShipperOrderDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvShipperOrderDetailList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindDetail(int.Parse(Request["OrderID"]));
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvShipperOrderDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail(int.Parse(Request["OrderID"]));
    }


    protected void gvShipperOrderDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShipperOrderDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail(int.Parse(Request["OrderID"]));
    }
    protected void gvShipperOrderDetailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindDetail(int.Parse(Request["OrderID"]));
    }

    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvTruckList.PageIndex = i;
                //数据绑定
                dataBindTruck(GetClientID());
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }
    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck(GetClientID());
    }

    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck(GetClientID());
    }
    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }

        dataBindTruck(GetClientID());
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }

    public string GetType(object typeID)
    {
        string model = string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }

    protected void btnCheck_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            if (Request["OrderID"] != null)
            {
                BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
                if (orderQuery != null)
                {
                    if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.NEW.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CEXPEDITEDTRUCK.ToString("d"))
                    {
                        SqlParameter[] parms = null;
                        List<SqlParameter> list = new List<SqlParameter>();

                        list.Add(new SqlParameter("@Status", Enums.ShippingOrderStatus.CHECK.ToString("d")));// ShippingOrder 运输队审核状态
                        list.Add(new SqlParameter("@CheckDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
                        list.Add(new SqlParameter("@CheckUser", Session["UserID"].ToString()));
                        list.Add(new SqlParameter("@OrderID", Request["OrderID"]));
                        list.Add(new SqlParameter("@Contractor", GetClientID().ToString()));
                        list.Add(new SqlParameter("@LastModUser", Session["UserID"].ToString()));
                        list.Add(new SqlParameter("@LastModDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd")));
                        list.Add(new SqlParameter("@Remark", string.Empty));
                        list.Add(new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CCONFIRM.ToString("d")));//BookingNoteDtl 运输队确认Job状态
                        SqlParameter parm = new SqlParameter("@ReturnValue",0);
                        parm.SqlDbType = SqlDbType.Int;
                        parm.Direction = ParameterDirection.Output;

                        list.Add(parm);
                        string sqlStr = "update BN_ShippingOrder set Status=@Status,CheckDate=@CheckDate,CheckUser=@CheckUser where PKID=@OrderID;";
                        sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CJDate=@CheckDate,CJUser=@CheckUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID)); ";
                        sqlStr += "insert into BN_SendTruck(SendNO,OrderID,Contractor,LastModUser,LastModDate,Remark) values(dbo.Fn_NextSendNO(),@OrderID,@Contractor,@LastModUser,@LastModDate,@Remark) SET @ReturnValue=@@Identity;";
                        sqlStr += "";
                        string[] trucks = Request["chkSelected"].Split(new char[] { ',' });
                        for (int i = 0; i < trucks.Length; i++)
                        {
                            list.Add(new SqlParameter("@TruckID" + i.ToString(), trucks[i]));

                            BN_TruckQuery query=truckManage.GetTruckByID(int.Parse(trucks[i]));
                            if (query != null)
                            {
                                list.Add(new SqlParameter("@Drive" + i.ToString(), query.Driver));
                            }
                            else
                            {
                                list.Add(new SqlParameter("@Drive" + i.ToString(), string.Empty));
                            }

                            //获取车型
                            for (int j = 0; j < gvTruckList.Rows.Count; j++)
                            {
                                HiddenField hidPKID = (HiddenField)gvTruckList.Rows[j].FindControl("hidPKID");
                                DropDownList ddlType = (DropDownList)gvTruckList.Rows[j].FindControl("ddlType");
                                if (trucks[i] == hidPKID.Value)
                                {
                                    list.Add(new SqlParameter("@TypeID" + i.ToString(),ddlType.SelectedValue));                                    
                                }
                            }

                            sqlStr += "insert into BN_SendTruckDtl(SendTruckID,TruckID,Driver,Remark,TypeID) values(@ReturnValue,@TruckID" + i.ToString() + ",@Drive" + i.ToString() + ",@Remark" + ",@TypeID" + i.ToString() + ")";
                        }

                        parms = list.ToArray();
                        if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                        {
                            Jscript.AlertAndRedirectInAjax(Resources.Messages.CheckSuccess, "PendingJobList.aspx", UpdatePanel1);
                        }
                        else
                        {
                            Jscript.AlertInAjax(Resources.Messages.CheckFailed, UpdatePanel1);
                        }
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.JobCheck, UpdatePanel1);
                        return;
                    }
                }
            }
        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.SendTruck, UpdatePanel1);
            return;
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("PendingJobList.aspx");
    }

    private DataTable GetModel()
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@Status", "1");
        string sqlSTr = "select * from Sy_ContainerModel where Status=@Status";

        return containerModelManage.GetModelList(sqlSTr, parms);

    }

    protected void gvTruckList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlType = (DropDownList)e.Row.FindControl("ddlType");
            HiddenField hidType = (HiddenField)e.Row.FindControl("hidType");
            ddlType.DataSource = GetModel();
            ddlType.DataTextField = "Model";
            ddlType.DataValueField = "PKID";
            ddlType.DataBind();
            ddlType.Items.Insert(0, new ListItem("请选择...","0"));

            ddlType.SelectedValue = hidType.Value;
        }
    }
}
